package cn.itsource.controller;

import cn.hutool.core.util.StrUtil;
import cn.itsource.basic.domain.JSONResult;
import cn.itsource.domain.es.Pet;
import cn.itsource.service.PetService;
import cn.itsource.vo.SearchQuery;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.maizi.es.annotation.HighlightColour;
import com.maizi.es.common.PageEsData;
import com.maizi.es.config.EsTemplate;
import com.maizi.es.util.EsQueryBuilders;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Objects;

@RequestMapping("pet")
@RestController
public class PetController {
    @Autowired
    PetService petService;
    @Autowired
    EsTemplate esTemplate;

    /**
    *1.请求方式:
    *2.url:findPage
    *3.请求参数:
    *4.响应参数:
    **/
    @PostMapping("findPage")
    public JSONResult findPage(@RequestBody SearchQuery query) throws IOException {
        Pet pet = new Pet();
        SearchSourceBuilder searchSource = EsQueryBuilders.createSearchSource(query.getPage(), query.getPageSize());
        if (StrUtil.isNotBlank(query.getKeyword())) {
            searchSource.query(QueryBuilders.matchQuery("name", query.getKeyword()));
        }else {
            searchSource.query( QueryBuilders.matchAllQuery ());
        }

        searchSource.highlighter(EsQueryBuilders.settingHighlight(HighlightColour.RED,"name"));
        PageEsData<Pet> classPageEsData = esTemplate.searchHighlightPage(searchSource, pet.index(), pet,"name");
        return JSONResult.success(classPageEsData);
//        Page page = new Page();
//        page.setSize(query.getPageSize());
//        page.setCurrent(query.getPage());
//        page.setSearchCount(true);
//        //2.条件查询
//        EntityWrapper example = new EntityWrapper<>();
//
//        // EntityWrapper.Criteria criteria = example.createCriteria();
//        //EntityWrapper.Criteria criteria1 = example.createCriteria();
//        //1.criteria 条件
//        //当状态不为空
//        if (Objects.nonNull(query.getState()))
//            example.eq("state",query.getState());
//        //当关键字不为空
//        if (StrUtil.isNotBlank(query.getKeyword()))
//            example.like("name","%"+query.getKeyword()+"%");
//
//        //当时间不为空
//        if (StrUtil.isNotBlank(query.getBetweenTime())) {
//            String[] time = query.getBetweenTime().split(",");
//
//            example.between("createTime",time[0],time[1] );
//        }
//        return JSONResult.success(petService.selectPage(page));
    }
    @GetMapping("/{id}")
    public JSONResult findOne(@PathVariable Long id){

        return JSONResult.success(petService.selectById(id));
    }
}
